﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public delegate void MyDownloadProgressChangedEventHandler(DataItem ditem);
    public delegate void AsyncCompletedEventHandler();

    
    public partial class Form1 : Form
    {
        MyDownloadProgressChangedEventHandler dc;

        public List<DataItem> _list;
        public List<Thread> _listthreads;
        public Form1()
        {
            InitializeComponent();

            //InitDataGridView(this.dataGridView1);

            AddGridViewColumns(this.dataGridView1);

            

            _list = new List<DataItem>();
            _listthreads = new List<Thread>();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadMethod method = new ThreadMethod();
            var dataitem = new DataItem()
            {
                Id = System.Guid.NewGuid().ToString(),
                Name = DateTime.Now.ToString(),
                Total = 100,
                DownTotal = 0,
                SkipTotal = 0,
                Msg = "开始任务"
            };
            var t = new Thread(StartDownLoad);
            t.Name = dataitem.Id;
            t.Start();
            _listthreads.Add(t);
            _list.Add(dataitem);
            dc += new MyDownloadProgressChangedEventHandler(DownLoadedProgressChange);
            this.dataGridView1.DataSource = _list;
            
        }

        void StartDownLoad()
        {
            foreach (var item in _list)
            {
                var dataitem = item ;

                 
                DownLoading(dataitem);
            }
        }
        void DownLoading(DataItem item)
        {
            int temp = item.DownTotal;
            for (int i = temp; i < item.Total; i++)
            {
                item.DownTotal = i;
                item.SynProgress = (item.DownTotal / item.Total) * 100 + "%";
                this.Invoke(dc, item);

                System.Threading.Thread.Sleep(1000);
            }

        }
        void DownLoadedProgressChange(DataItem item)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells["Id"].Value.ToString() == item.Id)
                {
                    row.Cells["DownTotal"].Value = item.DownTotal;
                    row.Cells["SynProgress"].Value = item.SynProgress;
                    row.Cells["Msg"].Value = string.Format("{0}",DateTime.Now);

                    Application.DoEvents();
                    break;
                }
            }
        }
        void DownLoadedCompleted()
        {

        }





        #region 初始化GridView

        void InitDataGridView(DataGridView dgv)
        {
            dgv.AutoGenerateColumns = false;//是否自动创建列
            dgv.AllowUserToAddRows = false;//是否允许添加行(默认：true)
            dgv.AllowUserToDeleteRows = false;//是否允许删除行(默认：true)
            dgv.AllowUserToResizeColumns = false;//是否允许调整大小(默认：true)
            dgv.AllowUserToResizeRows = false;//是否允许调整行大小(默认：true)
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列宽模式(当前填充)(默认：DataGridViewAutoSizeColumnsMode.None)
            dgv.BackgroundColor = System.Drawing.Color.White;//背景色(默认：ControlDark)
            dgv.BorderStyle = BorderStyle.Fixed3D;//边框样式(默认：BorderStyle.FixedSingle)
            dgv.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;//单元格边框样式(默认：DataGridViewCellBorderStyle.Single)
            dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;//列表头样式(默认：DataGridViewHeaderBorderStyle.Single)
            dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;//是否允许调整列大小(默认：DataGridViewColumnHeadersHeightSizeMode.EnableResizing)
            dgv.ColumnHeadersHeight = 30;//列表头高度(默认：20)
            dgv.MultiSelect = false;//是否支持多选(默认：true)
            dgv.ReadOnly = true;//是否只读(默认：false)
            dgv.RowHeadersVisible = false;//行头是否显示(默认：true)
            dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//选择模式(默认：DataGridViewSelectionMode.CellSelect)
        }

        #endregion

        #region 添加GridView列

        /// <summary>
        /// 正在同步列表
        /// </summary>
        void AddGridViewColumns(DataGridView dgv)
        {
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "Id",
                HeaderText = "Id",
                Visible = false,
                Name = "Id"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
                DataPropertyName = "Name",
                HeaderText = "名",
                Name = "Name"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "Total",
                HeaderText = "总数",
                Name = "Total",
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "DownTotal",
                HeaderText = "速度",
                Name = "DownTotal"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "SynProgress",
                HeaderText = "进度",
                Name = "SynProgress"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "SkipTotal",
                HeaderText = "跳过数量",
                Visible = false,
                Name = "SkipTotal"
            });
            dgv.Columns.Add(new DataGridViewTextBoxColumn()
            {
                DataPropertyName = "Msg",
                HeaderText = "说明",
                Visible = false,
                Name = "Msg"
            });
        }

        #endregion
    }
    public class DataItem
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public int Total { get; set; }
        public int DownTotal { get; set; }
        public int SkipTotal { get; set; }
        public string SynProgress { get; set; }
        public string Msg { get; set; }
        public DataItem()
        { }
        public DataItem(object[] objectArr)
        {
            int i = 0;
            Id = objectArr[i].ToString(); i++;
            Name = objectArr[i].ToString(); i++;
            Total = Convert.ToInt32(objectArr[i].ToString()); i++;
            DownTotal = Convert.ToInt32(objectArr[i].ToString()); i++;
            SkipTotal = Convert.ToInt32(objectArr[i].ToString()); i++;
            SynProgress = objectArr[i].ToString(); i++;
            Msg = objectArr[i].ToString(); i++;
        }
    }

    public class ThreadMethod
    {
        /// <summary>  
        /// 线程开始事件  
        /// </summary>  
        public event EventHandler threadStartEvent;
        /// <summary>  
        /// 线程执行时事件  
        /// </summary>  
        public event EventHandler threadEvent;
        /// <summary>  
        /// 线程结束事件  
        /// </summary>  
        public event EventHandler threadEndEvent;

        public void runMethod()
        {
            int count = 100;      //执行多少次  
            threadStartEvent.Invoke(count, new EventArgs());//通知主界面,我开始了,count用来设置进度条的最大值  
            for (int i = 0; i < count; i++)
            {
                Thread.Sleep(100);//休息100毫秒,模拟执行大数据量操作  
                threadEvent.Invoke(i, new EventArgs());//通知主界面我正在执行,i表示进度条当前进度  
            }
            threadEndEvent.Invoke(new object(), new EventArgs());//通知主界面我已经完成了  
        }
    }
}
